package com.corddt.controller;

import com.corddt.model.User;
import com.corddt.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String home() {
        log.info("Accessing home page");
        return "index";
    }

    @GetMapping("/login")
    public String showLoginForm(Model model) {
        model.addAttribute("user", new User());
        return "login";
    }

    @PostMapping("/login")
    public String login(@ModelAttribute User user, Model model) {
        log.info("User login attempt: {}", user);
        User loggedInUser = userService.login(user.getUsername(), user.getPassword());
        if (loggedInUser != null) {
            log.info("User logged in successfully: {}", loggedInUser);
            return "redirect:/home";
        } else {
            log.warn("User login failed: {}", user);
            model.addAttribute("errorMessage", "Invalid username or password");
            return "login";
        }
    }

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String register(@ModelAttribute User user) {
        log.info("Registering user: {}", user);
        if (user.getUsername() != null && user.getPassword() != null) {
            userService.register(user);
            log.info("User registered successfully: {}", user);
            return "redirect:/login";
        } else {
            log.warn("Invalid user registration: {}", user);
            return "redirect:/register";
        }
    }

    @GetMapping("/home")
    public String home(Model model) {
        return "home";
    }
}